<template>
  <view class="index-container">
    <!-- 用户信息栏 -->
    <view class="user-info-bar">
      <view class="user-avatar">
        <image 
          :src="userAvatar || '/static/images/default-avatar.png'" 
          class="avatar-img"
        />
      </view>
      <view class="user-detail">
        <text class="user-name">{{ userName || '请先登录' }}</text>
        <text class="user-role">智慧社区居民</text>
        <!-- 调试信息 -->
        <text class="debug-info" v-if="showDebugInfo">登录状态: {{ isLoggedIn ? '已登录' : '未登录' }}</text>
      </view>
      <view class="header-actions">
        <text class="message-icon">📧</text>
        <text class="settings-icon" @click="toggleDebugInfo">⚙️</text>
        <text class="test-icon" @click="goToAuthTest">🧪</text>
      </view>
    </view>

    <!-- 统计数据卡片 -->
    <view class="stats-cards">
      <view class="stats-card stats-card-1">
        <text class="stats-icon">📅</text>
        <text class="stats-number">{{ todayEvents }}</text>
        <text class="stats-label">今日事件</text>
      </view>
      <view class="stats-card stats-card-2">
        <text class="stats-icon">📋</text>
        <text class="stats-number">{{ pendingTasks }}</text>
        <text class="stats-label">待处理</text>
      </view>
      <view class="stats-card stats-card-3">
        <text class="stats-icon">👥</text>
        <text class="stats-number">{{ onlineUsers }}</text>
        <text class="stats-label">在线用户</text>
      </view>
      <view class="stats-card stats-card-4">
        <text class="stats-icon">✅</text>
        <text class="stats-number">{{ systemStatus }}</text>
        <text class="stats-label">系统状态</text>
      </view>
    </view>

    <!-- 功能入口网格 -->
    <view class="function-grid">
      <view class="grid-title">功能服务</view>
      <view class="grid-container">
        <view 
          class="grid-item" 
          v-for="item in accessibleFunctions" 
          :key="item.id"
          @click="navigateToFunction(item)"
        >
          <text class="grid-icon">{{ item.icon }}</text>
          <text class="grid-label">{{ item.label }}</text>
        </view>
      </view>
    </view>

    <!-- 通知公告 -->
    <view class="notice-section">
      <view class="section-header">
        <text class="section-title">通知公告</text>
        <text class="section-more" @click="goToNoticeList">查看更多</text>
      </view>
      <view class="notice-list">
        <view 
          class="notice-item" 
          v-for="notice in noticeList" 
          :key="notice.id"
          @click="goToNoticeDetail(notice)"
        >
          <text class="notice-icon">📢</text>
          <view class="notice-content">
            <text class="notice-title">{{ notice.title }}</text>
            <text class="notice-time">{{ formatTime(notice.createTime) }}</text>
          </view>
          <text class="notice-arrow">></text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore, useAuthStore } from '@/store'
import { formatRelativeTime } from '@/utils/format'
import { hasMenuPermission } from '@/utils/permission'
import { smartNavigate } from '@/utils/navigation'

export default {
  name: 'IndexPage',
  data() {
    return {
      todayEvents: 5,
      pendingTasks: 3,
      onlineUsers: 128,
      systemStatus: '正常',
      showDebugInfo: false, // 调试信息显示状态
      // 调试信息
      debugInfo: {
        authStoreLoggedIn: false,
        userStoreUserName: '',
        localUserInfo: null,
        localToken: ''
      },
      functionList: [
        { id: 1, icon: '🛡️', label: '安防管理', path: '/pages/security/security', permission: null },
        { id: 2, icon: '🏠', label: '物业服务', path: '/pages/property/property', permission: null },
        { id: 3, icon: '🚗', label: '停车管理', path: '/pages/parking/parking', permission: null },
        { id: 4, icon: '🚨', label: '紧急求助', path: '/pages/emergency/emergency', permission: null },
        { id: 5, icon: '💬', label: '投诉建议', path: '/pages/complaint/complaint', permission: null },
        { id: 6, icon: '💰', label: '在线支付', path: '/pages/payment/payment', permission: null },
        { id: 7, icon: '🤝', label: '社区服务', path: '/pages/services/services', permission: null },
        { id: 8, icon: '📊', label: '数据分析', path: '/pages/services/services', permission: null },
        { id: 9, icon: '👥', label: '用户管理', path: '/pages/profile/index', permission: null },
        { id: 10, icon: '⚙️', label: '更多功能', path: '/pages/services/services', permission: null }
      ],
      noticeList: [
        {
          id: 1,
          title: '社区停水通知',
          createTime: '2025-01-21 10:00:00'
        },
        {
          id: 2,
          title: '春节放假安排',
          createTime: '2025-01-20 15:30:00'
        },
        {
          id: 3,
          title: '物业费缴费提醒',
          createTime: '2025-01-19 09:00:00'
        }
      ]
    }
  },
  
  computed: {
    userName() {
      try {
        const userStore = useUserStore()
        const authStore = useAuthStore()
        const userName = userStore.userName || authStore.username
        return userName || '请先登录'
      } catch (error) {
        console.warn('获取用户名失败:', error)
        return '请先登录'
      }
    },
    userAvatar() {
      try {
        const userStore = useUserStore()
        const authStore = useAuthStore()
        const avatar = userStore.userAvatar || authStore.avatar
        return avatar || '/static/images/default-avatar.png'
      } catch (error) {
        console.warn('获取用户头像失败:', error)
        return '/static/images/default-avatar.png'
      }
    },
    isLoggedIn() {
      try {
        const authStore = useAuthStore()
        return authStore.isLoggedIn || false
      } catch (error) {
        console.warn('获取登录状态失败:', error)
        return false
      }
    },
    accessibleFunctions() {
      try {
        const authStore = useAuthStore()
        
        // 如果未登录，返回空数组
        if (!authStore.isLoggedIn) {
          return []
        }
        
        // 主菜单全部显示，不进行权限过滤
        return this.functionList
      } catch (error) {
        console.warn('获取可访问功能失败:', error)
        return []
      }
    }
  },
  
  onLoad() {
    // 延迟初始化，确保store已完全初始化
    setTimeout(() => {
      this.initData()
    }, 50)
  },
  
  onShow() {
    this.refreshData()
  },
  
  methods: {
    /**
     * 初始化数据
     */
    async initData() {
      try {
        // 检查登录状态
        const authStore = useAuthStore()
        
        // 收集调试信息
        this.debugInfo.authStoreLoggedIn = authStore.isLoggedIn
        this.debugInfo.localToken = uni.getStorageSync('token') || ''
        this.debugInfo.localUserInfo = uni.getStorageSync('userInfo') || null
        
        // 如果本地有token但authStore显示未登录，尝试恢复登录状态
        if (!authStore.isLoggedIn && this.debugInfo.localToken) {
          console.log('检测到本地token，尝试恢复登录状态')
          await authStore.initAuth()
        }
        
        // 再次检查登录状态
        if (authStore.isLoggedIn) {
          try {
            const userStore = useUserStore()
            await userStore.getLoginInfo()
            this.debugInfo.userStoreUserName = userStore.userName
            console.log('用户信息初始化成功:', userStore.userName)
            console.log('调试信息:', this.debugInfo)
            
            // 如果userStore中没有用户信息，尝试从authStore获取
            if (!userStore.userName && authStore.userInfo) {
              userStore.syncUserInfo(authStore.userInfo)
              console.log('从authStore同步用户信息:', authStore.userInfo)
            }
          } catch (userError) {
            console.error('用户信息初始化失败:', userError)
            // 用户信息初始化失败，但authStore仍然有效，继续执行
          }
          
          // 加载页面数据
          await this.loadDashboardData()
        } else {
          console.log('用户未登录，跳转到登录页面')
          uni.reLaunch({
            url: '/pages/login/login'
          })
          return
        }
      } catch (error) {
        console.error('初始化数据失败:', error)
        // 如果初始化失败，跳转到登录页面
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    /**
     * 刷新数据
     */
    async refreshData() {
      await this.loadDashboardData()
    },
    
    /**
     * 加载仪表盘数据
     */
    async loadDashboardData() {
      // 这里可以调用API获取实际数据
      // 目前使用模拟数据
      this.todayEvents = Math.floor(Math.random() * 10) + 1
      this.pendingTasks = Math.floor(Math.random() * 5) + 1
      this.onlineUsers = Math.floor(Math.random() * 200) + 50
    },
    
    /**
     * 导航到功能页面
     */
    navigateToFunction(item) {
      if (item.path) {
        // 暂时允许所有用户访问所有功能
        // TODO: 后续根据具体需求设置权限控制
        console.log('导航到功能页面:', item.path)
        
        // 使用智能页面跳转工具函数
        smartNavigate(item.path)
      } else {
        uni.showToast({
          title: '功能开发中',
          icon: 'none'
        })
      }
    },
    
    /**
     * 前往通知列表
     */
    goToNoticeList() {
      uni.showToast({
        title: '通知功能开发中',
        icon: 'none'
      })
    },
    
    /**
     * 前往通知详情
     */
    goToNoticeDetail(notice) {
      uni.showToast({
        title: '通知详情功能开发中',
        icon: 'none'
      })
    },
    
    /**
     * 格式化时间
     */
    formatTime(time) {
      return formatRelativeTime(time)
    },

    /**
     * 切换调试信息显示
     */
    toggleDebugInfo() {
      this.showDebugInfo = !this.showDebugInfo
    },
    
    /**
     * 前往认证测试页面
     */
    goToAuthTest() {
      uni.navigateTo({
        url: '/pages/test/auth-test'
      })
    },
    
    /**
     * 根据路径获取权限编码
     */
    getPermissionCodeByPath(path) {
      const permissionMap = {
        '/pages/security/security': 'mobile:security:menu',
        '/pages/property/property': 'mobile:property:menu',
        '/pages/parking/parking': 'mobile:parking:menu',
        '/pages/emergency/emergency': 'mobile:emergency:menu',
        '/pages/complaint/complaint': 'mobile:complaint:menu',
        '/pages/payment/payment': 'mobile:payment:menu',
        '/pages/services/services': 'mobile:services:menu',
        '/pages/profile/index': 'mobile:profile:menu'
      }
      
      return permissionMap[path] || null
    }
  }
}
</script>

<style lang="scss" scoped>
.index-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 100rpx;
}

.user-info-bar {
  display: flex;
  align-items: center;
  padding: 40rpx 32rpx 20rpx;
  color: white;
  
  .user-avatar {
    margin-right: 24rpx;
    
    .avatar-img {
      width: 96rpx;
      height: 96rpx;
      border-radius: 50%;
      border: 4rpx solid rgba(255, 255, 255, 0.3);
    }
  }
  
  .user-detail {
    flex: 1;
    
    .user-name {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 8rpx;
    }
    
    .user-role {
      font-size: 28rpx;
      opacity: 0.8;
    }
  }
  
  .header-actions {
    display: flex;
    gap: 24rpx;
    
    .message-icon,
    .settings-icon,
    .test-icon {
      font-size: 48rpx;
    }
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16rpx;
  padding: 0 32rpx 40rpx;
  margin-top: -20rpx;
  
  .stats-card {
    background: white;
    border-radius: 24rpx;
    padding: 32rpx;
    text-align: center;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
    
    .stats-icon {
      display: block;
      font-size: 48rpx;
      margin-bottom: 16rpx;
    }
    
    .stats-number {
      display: block;
      font-size: 48rpx;
      font-weight: bold;
      color: #262626;
      margin-bottom: 8rpx;
    }
    
    .stats-label {
      font-size: 24rpx;
      color: #8c8c8c;
    }
  }
  
  .stats-card-1 { background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%); color: white; }
  .stats-card-2 { background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%); color: white; }
  .stats-card-3 { background: linear-gradient(135deg, #45b7d1 0%, #96c93d 100%); color: white; }
  .stats-card-4 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; }
}

.function-grid {
  background: white;
  border-radius: 32rpx 32rpx 0 0;
  margin-top: 40rpx;
  padding: 40rpx 32rpx;
  
  .grid-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #262626;
    margin-bottom: 32rpx;
  }
  
  .grid-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 32rpx;
    
    .grid-item {
      text-align: center;
      
      .grid-icon {
        display: block;
        font-size: 80rpx;
        margin-bottom: 16rpx;
      }
      
      .grid-label {
        font-size: 24rpx;
        color: #262626;
      }
    }
  }
}

.notice-section {
  background: white;
  margin-top: 24rpx;
  padding: 40rpx 32rpx;
  
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32rpx;
    
    .section-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #262626;
    }
    
    .section-more {
      font-size: 28rpx;
      color: #2d8cf0;
    }
  }
  
  .notice-list {
    .notice-item {
      display: flex;
      align-items: center;
      padding: 24rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .notice-icon {
        font-size: 48rpx;
        margin-right: 24rpx;
      }
      
      .notice-content {
        flex: 1;
        
        .notice-title {
          display: block;
          font-size: 28rpx;
          color: #262626;
          margin-bottom: 8rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .notice-time {
          font-size: 24rpx;
          color: #8c8c8c;
        }
      }
      
      .notice-arrow {
        font-size: 24rpx;
        color: #8c8c8c;
      }
    }
  }
}
</style> 